package org.finesys.common.security.authentication.gitee;

import java.util.Map;

import org.finesys.common.constants.SecurityConstants;
import org.finesys.common.security.authentication.base.OAuth2ResourceOwnerBaseAuthenticationProvider;
import org.finesys.common.security.client.core.endpoint.OAuth2GiteeParameterNames;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.AuthorizationGrantType;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.OAuth2ErrorCodes;
import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames;
import org.springframework.security.oauth2.server.authorization.client.RegisteredClient;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class OAuth2GiteeAuthenticationProvider extends OAuth2ResourceOwnerBaseAuthenticationProvider<OAuth2GiteeAuthenticationToken> {


    public OAuth2GiteeAuthenticationProvider(HttpSecurity httpSecurity) {
        super(httpSecurity);
    }

    @Override
    public UsernamePasswordAuthenticationToken buildToken(Authentication authentication, Map<String, Object> requestParameters) {
        String appId = (String) requestParameters.get(OAuth2GiteeParameterNames.APPID);
        String code = (String) requestParameters.get(OAuth2ParameterNames.CODE);
        return new UsernamePasswordAuthenticationToken(appId, code);
    }

    @Override
    public boolean supports(Class<?> authentication) {
        boolean supports = OAuth2GiteeAuthenticationToken.class.isAssignableFrom(authentication);
        if (log.isDebugEnabled()) {
            log.debug("supports  authentication=[{}] returning {}", authentication, supports);
        }
        return supports;
    }

    @Override
    public void checkClient(RegisteredClient registeredClient) {
        assert registeredClient != null;
        if (!registeredClient.getAuthorizationGrantTypes().contains(new AuthorizationGrantType(SecurityConstants.GITEE))) {
            throw new OAuth2AuthenticationException(OAuth2ErrorCodes.UNAUTHORIZED_CLIENT);
        }
    }
}
